package com.zgzg.shop.pay.business.common.utils;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;
import java.util.function.Supplier;

/**
 * @description:
 * @version: 1.0.0
 */
@Slf4j
public class ThreadPoolExecutorUtils {
    /**
     * 线程工厂
     */
    private static ThreadFactory threadFactory = new ThreadFactoryBuilder().setNameFormat("asyncPool").build();
    /**
     * 一级线程池，主线程使用的异步线程池
     */
    private static ExecutorService firstExecutorService = new ThreadPoolExecutor(8, 32, 10000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(512), threadFactory);
    /**
     * 二级线程池，子线程使用的异步线程池
     * 为什么要分一二级？是避免父子线程分使用同一个线程池，资源竞争引起的死锁
     */
    private static ExecutorService secondExecutorService = new ThreadPoolExecutor(8, 32, 10000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(512), threadFactory);


    public static ExecutorService getFirstExecutorService() {
        return firstExecutorService;
    }

    public static ExecutorService getSecondExecutorService() {
        return secondExecutorService;
    }

    public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier) {
        return CompletableFuture.supplyAsync(supplier, getFirstExecutorService());
    }

    public static <U> U get(CompletableFuture<U> completableFuture) {
        return get(completableFuture, 3000);
    }

    public static <U> U get(CompletableFuture<U> completableFuture, long timeout) {
        if (completableFuture == null) {
            return null;
        }
        try {
            return completableFuture.get(timeout, TimeUnit.MILLISECONDS);
        } catch (Exception e) {
            log.error("ThreadPoolExecutorUtils.get Exception", e);
        }
        return null;
    }
}
